/**
 * @description 数据备份和恢复工具
 * @author 张一依有把越女剑
 * @date 2025-04-16
 */

import { logger } from './miniprogramErrorHandler.js'

// 数据备份管理器
export class DataBackupManager {
	constructor() {
		this.backupKeys = [
			'examRecords',
			'userInfo',
			'adminToken',
			'app_logs'
		]
		this.maxBackups = 5 // 最多保留5个备份
	}
	
	// 创建完整备份
	async createFullBackup() {
		try {
			const backupData = {
				timestamp: Date.now(),
				version: '1.0.0',
				data: {}
			}
			
			// 收集所有需要备份的数据
			for (const key of this.backupKeys) {
				try {
					const data = uni.getStorageSync(key)
					if (data) {
						backupData.data[key] = data
					}
				} catch (error) {
					logger.warn(`Failed to backup ${key}:`, error)
				}
			}
			
			// 生成备份ID
			const backupId = `backup_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
			
			// 保存备份
			uni.setStorageSync(backupId, backupData)
			
			// 更新备份列表
			this.updateBackupList(backupId)
			
			logger.info('Full backup created successfully', { backupId })
			
			return {
				success: true,
				backupId,
				timestamp: backupData.timestamp
			}
		} catch (error) {
			logger.error('Failed to create backup:', error)
			return {
				success: false,
				error: error.message
			}
		}
	}
	
	// 更新备份列表
	updateBackupList(newBackupId) {
		try {
			let backupList = uni.getStorageSync('backup_list') || []
			backupList.push({
				id: newBackupId,
				timestamp: Date.now()
			})
			
			// 按时间排序，保留最新的备份
			backupList.sort((a, b) => b.timestamp - a.timestamp)
			
			// 删除超出限制的旧备份
			if (backupList.length > this.maxBackups) {
				const oldBackups = backupList.slice(this.maxBackups)
				oldBackups.forEach(backup => {
					uni.removeStorageSync(backup.id)
				})
				backupList = backupList.slice(0, this.maxBackups)
			}
			
			uni.setStorageSync('backup_list', backupList)
		} catch (error) {
			logger.error('Failed to update backup list:', error)
		}
	}
	
	// 获取备份列表
	getBackupList() {
		try {
			const backupList = uni.getStorageSync('backup_list') || []
			return backupList.map(backup => {
				const backupData = uni.getStorageSync(backup.id)
				return {
					id: backup.id,
					timestamp: backup.timestamp,
					date: new Date(backup.timestamp).toLocaleString('zh-CN'),
					size: JSON.stringify(backupData).length,
					version: backupData?.version || 'unknown'
				}
			})
		} catch (error) {
			logger.error('Failed to get backup list:', error)
			return []
		}
	}
	
	// 恢复备份
	async restoreBackup(backupId) {
		try {
			const backupData = uni.getStorageSync(backupId)
			if (!backupData) {
				throw new Error('Backup not found')
			}
			
			// 创建当前数据的备份（以防恢复失败）
			const rollbackBackup = await this.createRollbackBackup()
			
			// 恢复数据
			const restoredKeys = []
			for (const [key, value] of Object.entries(backupData.data)) {
				try {
					uni.setStorageSync(key, value)
					restoredKeys.push(key)
				} catch (error) {
					logger.warn(`Failed to restore ${key}:`, error)
				}
			}
			
			logger.info('Backup restored successfully', { 
				backupId, 
				restoredKeys,
				rollbackBackup: rollbackBackup.backupId
			})
			
			return {
				success: true,
				restoredKeys,
				rollbackBackup: rollbackBackup.backupId
			}
		} catch (error) {
			logger.error('Failed to restore backup:', error)
			return {
				success: false,
				error: error.message
			}
		}
	}
	
	// 创建回滚备份
	async createRollbackBackup() {
		const rollbackData = {
			timestamp: Date.now(),
			version: '1.0.0',
			type: 'rollback',
			data: {}
		}
		
		for (const key of this.backupKeys) {
			try {
				const data = uni.getStorageSync(key)
				if (data) {
					rollbackData.data[key] = data
				}
			} catch (error) {
				logger.warn(`Failed to create rollback for ${key}:`, error)
			}
		}
		
		const backupId = `rollback_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
		uni.setStorageSync(backupId, rollbackData)
		
		return { backupId, timestamp: rollbackData.timestamp }
	}
	
	// 删除备份
	deleteBackup(backupId) {
		try {
			uni.removeStorageSync(backupId)
			
			// 从备份列表中移除
			let backupList = uni.getStorageSync('backup_list') || []
			backupList = backupList.filter(backup => backup.id !== backupId)
			uni.setStorageSync('backup_list', backupList)
			
			logger.info('Backup deleted successfully', { backupId })
			return { success: true }
		} catch (error) {
			logger.error('Failed to delete backup:', error)
			return { success: false, error: error.message }
		}
	}
	
	// 导出备份数据
	exportBackup(backupId) {
		try {
			const backupData = uni.getStorageSync(backupId)
			if (!backupData) {
				throw new Error('Backup not found')
			}
			
			const exportData = JSON.stringify(backupData, null, 2)
			return {
				success: true,
				data: exportData,
				filename: `exam_backup_${new Date(backupData.timestamp).toISOString().split('T')[0]}.json`
			}
		} catch (error) {
			logger.error('Failed to export backup:', error)
			return { success: false, error: error.message }
		}
	}
	
	// 导入备份数据
	async importBackup(backupDataString) {
		try {
			const backupData = JSON.parse(backupDataString)
			
			// 验证备份数据格式
			if (!backupData.timestamp || !backupData.data) {
				throw new Error('Invalid backup format')
			}
			
			// 生成新的备份ID
			const backupId = `imported_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
			
			// 保存导入的备份
			uni.setStorageSync(backupId, backupData)
			
			// 更新备份列表
			this.updateBackupList(backupId)
			
			logger.info('Backup imported successfully', { backupId })
			
			return {
				success: true,
				backupId,
				timestamp: backupData.timestamp
			}
		} catch (error) {
			logger.error('Failed to import backup:', error)
			return { success: false, error: error.message }
		}
	}
	
	// 自动备份
	async autoBackup() {
		try {
			// 检查是否需要自动备份
			const lastBackup = this.getLastBackupTime()
			const now = Date.now()
			const backupInterval = 24 * 60 * 60 * 1000 // 24小时
			
			if (now - lastBackup > backupInterval) {
				const result = await this.createFullBackup()
				if (result.success) {
					logger.info('Auto backup completed', result)
				}
				return result
			}
			
			return { success: true, message: 'No backup needed' }
		} catch (error) {
			logger.error('Auto backup failed:', error)
			return { success: false, error: error.message }
		}
	}
	
	// 获取最后备份时间
	getLastBackupTime() {
		try {
			const backupList = uni.getStorageSync('backup_list') || []
			if (backupList.length > 0) {
				return Math.max(...backupList.map(backup => backup.timestamp))
			}
			return 0
		} catch (error) {
			return 0
		}
	}
	
	// 清理所有备份
	clearAllBackups() {
		try {
			const backupList = uni.getStorageSync('backup_list') || []
			backupList.forEach(backup => {
				uni.removeStorageSync(backup.id)
			})
			uni.removeStorageSync('backup_list')
			
			logger.info('All backups cleared')
			return { success: true }
		} catch (error) {
			logger.error('Failed to clear backups:', error)
			return { success: false, error: error.message }
		}
	}
	
	// 获取存储使用情况
	getStorageInfo() {
		try {
			const info = uni.getStorageInfoSync()
			const backupList = this.getBackupList()
			const backupSize = backupList.reduce((total, backup) => total + backup.size, 0)
			
			return {
				totalSize: info.currentSize,
				backupCount: backupList.length,
				backupSize,
				availableSpace: info.limitSize - info.currentSize
			}
		} catch (error) {
			logger.error('Failed to get storage info:', error)
			return null
		}
	}
}

export const dataBackupManager = new DataBackupManager()

// 数据同步管理器（用于多设备同步）
export class DataSyncManager {
	constructor() {
		this.syncEndpoint = '' // 同步服务器端点
		this.syncKey = 'last_sync_time'
	}
	
	// 上传数据到云端
	async uploadData() {
		// 这里可以实现云端同步逻辑
		// 比如上传到微信云开发、uniCloud等
	}
	
	// 从云端下载数据
	async downloadData() {
		// 这里可以实现从云端下载数据的逻辑
	}
	
	// 同步数据
	async syncData() {
		try {
			// 实现数据同步逻辑
			const lastSyncTime = uni.getStorageSync(this.syncKey) || 0
			const now = Date.now()
			
			// 检查是否需要同步
			if (now - lastSyncTime > 60 * 60 * 1000) { // 1小时同步一次
				await this.uploadData()
				await this.downloadData()
				uni.setStorageSync(this.syncKey, now)
				
				logger.info('Data sync completed')
				return { success: true }
			}
			
			return { success: true, message: 'No sync needed' }
		} catch (error) {
			logger.error('Data sync failed:', error)
			return { success: false, error: error.message }
		}
	}
}
